package com.java.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.java.dao.LoginDao;
import com.java.ext.MyButton;
import com.java.utils.UserSession;

/**
* @ClassName: LoginWindow
* @Description: 系统登陆界面
*
 */
public class LoginWindow extends BaseJFrame {

	private static final long serialVersionUID = 1L;
	// 创建组件
	private JLabel userLabel, passLabel;
	private JTextField userField;
	private JPasswordField passField;
	private MyButton loginButton;
	private JPanel panel;

	// 构造函数
	public LoginWindow() {
		final JFrame thisFrame = this;
		// 设置窗口属性
		setTitle("To Do Management System");
		setSize(300, 230);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null); // 居中显示

		// 创建组件并添加到布局中
		panel = new JPanel();
		panel.setLayout(null);

		userLabel = new JLabel("username:");
		userLabel.setBounds(10, 20, 80, 25);
		panel.add(userLabel);

		userField = new JTextField(20);
		userField.setText("admin");
		userField.setBounds(100, 20, 165, 25);
		panel.add(userField);
		

		passLabel = new JLabel("password:");
		passLabel.setBounds(10, 60, 80, 25);
		panel.add(passLabel);

		passField = new JPasswordField(20);
		passField.setBounds(100, 60, 165, 25);
		passField.setText("123456");
		panel.add(passField);

		loginButton = new MyButton("Login");
		loginButton.setBounds(100, 140, 80, 25);
		loginButton.primary(); 
		panel.add(loginButton);

		loginButton.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
            	String username = userField.getText();
    			String password = new String(passField.getPassword());
            	if("".equals(username)) {
            		warning("Input username");
            		return;
            	}
            	if("".equals(password)) {
            		warning("Input password");
            		return;
            	}
            	// 如果返回ID大于0则表示登录成功
            	int loginId = LoginDao.login(username, password);
            	if(loginId == 0) {
            		warning("Account does not exist");
            		return;
            	}
            	if(loginId == -1) {
            		warning("Password error");
            		return;
            	}
    	        UserSession session = UserSession.getInstance();
    	        session.setVal(loginId, username, password);
    	        new AdminMainWindow();
    	        thisFrame.dispose();
            }  
        }); 
		
		// 将面板添加到窗口中
		add(panel);
		
		setVisible(true);
	}
	
}